<?php
declare(strict_types=1);

namespace app\validate;

use think\Validate;

class PaymentConfigValidate extends Validate
{
    protected $rule = [
        'payment_method' => 'require|in:1,2,3',
        'payment_config' => 'require|array',
        'status' => 'require|in:1,2',
        'id' => 'require|number'
    ];

    protected $message = [
        'payment_method.require' => '请选择支付方式',
        'payment_method.in' => '支付方式不正确',
        'payment_config.require' => '请填写支付配置',
        'payment_config.array' => '支付配置格式不正确',
        'status.require' => '请选择状态',
        'status.in' => '状态值不正确',
        'id.require' => '配置ID不能为空',
        'id.number' => '配置ID必须为数字'
    ];

    protected $scene = [
        'save' => ['payment_method', 'payment_config', 'status'],
        'update_status' => ['id', 'status'],
        'delete' => ['id']
    ];

    /**
     * 验证微信支付配置
     */
    protected function checkWechatConfig($value): bool
    {
        if ($value['payment_method'] != 1) {
            return true;
        }

        $required = ['app_id', 'mch_id', 'key', 'cert_path', 'key_path'];
        foreach ($required as $field) {
            if (empty($value['payment_config'][$field])) {
                return false;
            }
        }

        return true;
    }

    /**
     * 验证支付宝配置
     */
    protected function checkAlipayConfig($value): bool
    {
        if ($value['payment_method'] != 2) {
            return true;
        }

        $required = ['app_id', 'private_key', 'public_key'];
        foreach ($required as $field) {
            if (empty($value['payment_config'][$field])) {
                return false;
            }
        }

        return true;
    }

    /**
     * 验证余额支付配置
     */
    protected function checkBalanceConfig($value): bool
    {
        if ($value['payment_method'] != 3) {
            return true;
        }

        return isset($value['payment_config']['enabled']);
    }

    /**
     * 保存场景验证
     */
    public function sceneSave(): PaymentConfigValidate
    {
        return $this->append([
            'payment_config' => function($value, $data) {
                switch ($data['payment_method']) {
                    case 1:
                        return $this->checkWechatConfig($data);
                    case 2:
                        return $this->checkAlipayConfig($data);
                    case 3:
                        return $this->checkBalanceConfig($data);
                    default:
                        return false;
                }
            }
        ]);
    }
} 